package com.idc.quotation.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.idc.common.util.JwtUtil;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");
		// System.out.println(JSON.toJSONString(request.getHeaderNames()));
		// System.out.println("===>" + request.getHeader("content-type"));
		// System.out.println("===>" + request.getParameter("test"));
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
			// String username = jwtUtil.extractUsername(token);
			// if (username != null && jwtUtil.validateToken(token, username)) {
			// // 通过用户身份信息，可以设置到请求中
			// request.setAttribute("username", username);
			// return true;
			// }
			if (jwtUtil.validateRedisToken(token)) {
				return true;
            }
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        return false;
    }
}
